﻿@using Microsoft.AspNetCore.Components.Authorization
@inject IStringLocalizer<BlockAuthorizate> Localizer

<div class="mb-3" style="height: 21px;">
    <Block OnQueryCondition="OnQueryUser" Name="Authorized">
        <div>@((MarkupString)Localizer["AuthorizateDiv1", UserName].Value)</div>
    </Block>
</div>
<Microsoft.AspNetCore.Components.Authorization.CascadingAuthenticationState>
    <Microsoft.AspNetCore.Components.Authorization.AuthorizeView>
        <Authorized>
            <div>@((MarkupString)Localizer["AuthorizateDiv2", context.User.Identity?.Name!].Value)</div>
        </Authorized>
        <NotAuthorized>
            <div>@((MarkupString)Localizer["AuthorizateDiv3"].Value)</div>
        </NotAuthorized>
    </Microsoft.AspNetCore.Components.Authorization.AuthorizeView>
</Microsoft.AspNetCore.Components.Authorization.CascadingAuthenticationState>
<Button Icon="@GetUser()" Text="@GetUserText()" OnClick="ToggleAuthor" class="mt-3" />

@code {
    [Inject]
    [NotNull]
    private AuthenticationStateProvider? AuthenticationStateProvider { get; set; }

    private bool IsAuth { get; set; }

    [NotNull]
    private string? UserName { get; set; }

    private async Task ToggleAuthor()
    {
        if (AuthenticationStateProvider is MockAuthenticationStateProvider mock)
        {
            if (!IsAuth)
            {
                mock.Login();
                var state = await mock.GetAuthenticationStateAsync();
                UserName = state.User.Identity?.Name;
                IsAuth = state.User.Identity?.IsAuthenticated ?? false;
            }
            else
            {
                mock.Logout();
                IsAuth = false;
                UserName = "";
            }
        }
    }

    private IEnumerable<string> Users { get; } = new string[] { "BootstrapBlazor" };

    private IEnumerable<string> Roles { get; } = new string[] { "User" };

    private string GetUser() => IsAuth ? "fa-solid fa-user-secret" : "fa-solid fa-user";

    private string GetUserText() => IsAuth ? Localizer["Logout"] : Localizer["Login"];

    private Task<bool> OnQueryUser(string name) => Task.FromResult(IsAuth);
}
